import api from '@/utils/api'
import { defineStore } from 'pinia'

// 本地存储键名
const STORAGE_KEYS = {
  SEARCH_KEYWORD: 'devenv_search_keyword',
  SELECTED_CATEGORY: 'devenv_selected_category',
  SELECTED_OS: 'devenv_selected_os',
  SELECTED_SOFTWARE: 'devenv_selected_software',
  SCRIPT_CONFIG: 'devenv_script_config',
  INSTALL_PATH: 'devenv_install_path'
}

// 本地存储工具函数
const storage = {
  get(key, defaultValue = null)
  {
    try
    {
      const value = localStorage.getItem(key)
      return value ? JSON.parse(value) : defaultValue
    } catch (error)
    {
      console.warn('Failed to get from localStorage:', error)
      return defaultValue
    }
  },

  set(key, value)
  {
    try
    {
      localStorage.setItem(key, JSON.stringify(value))
    } catch (error)
    {
      console.warn('Failed to set to localStorage:', error)
    }
  },

  remove(key)
  {
    try
    {
      localStorage.removeItem(key)
    } catch (error)
    {
      console.warn('Failed to remove from localStorage:', error)
    }
  }
}

export const useSoftwareStore = defineStore('software', {
  state: () => ({
    // 软件列表
    softwareList: [],
    categories: [],
    selectedSoftware: storage.get(STORAGE_KEYS.SELECTED_SOFTWARE, []),

    // 加载状态
    loading: false,

    // 搜索 - 从本地存储恢复
    searchKeyword: storage.get(STORAGE_KEYS.SEARCH_KEYWORD, ''),
    selectedCategory: storage.get(STORAGE_KEYS.SELECTED_CATEGORY, ''),
    selectedOs: storage.get(STORAGE_KEYS.SELECTED_OS, 'windows'),

    // 脚本生成配置 - 从本地存储恢复
    scriptConfig: storage.get(STORAGE_KEYS.SCRIPT_CONFIG, {
      os: 'windows',
      installPath: 'C:\\DevEnv',
      mirrorRegion: 'CN',
      enableResume: true,
      enableVerification: true,
      enableAutoPath: true
    }),

    // 脚本选项（保持向后兼容）
    scriptOptions: {
      enableResume: true,
      enableVerification: true,
      enableAutoPath: true,
      mirrorRegion: 'CN'
    },
    installPath: storage.get(STORAGE_KEYS.INSTALL_PATH, 'C:\\DevEnv'),

    // 生成的脚本
    generatedScript: null
  }),

  getters: {
    // 过滤后的软件列表 - 添加缓存优化
    filteredSoftware: (state) =>
    {
      // 如果没有筛选条件，直接返回原列表
      if (!state.selectedCategory && !state.selectedOs && !state.searchKeyword)
      {
        return state.softwareList
      }

      let filtered = state.softwareList

      // 按分类过滤
      if (state.selectedCategory)
      {
        filtered = filtered.filter(software =>
          software.category === state.selectedCategory
        )
      }

      // 按操作系统过滤
      if (state.selectedOs)
      {
        filtered = filtered.filter(software =>
        {
          // 如果软件没有指定支持的操作系统，则认为支持所有操作系统
          if (!software.osSupport || software.osSupport === null)
          {
            return true
          }

          // 处理大小写不匹配问题
          const osSupport = software.osSupport.toLowerCase()
          const selectedOs = state.selectedOs.toLowerCase()
          return osSupport.includes(selectedOs)
        })
      }

      // 按关键词搜索
      if (state.searchKeyword)
      {
        const keyword = state.searchKeyword.toLowerCase().trim()
        if (keyword)
        {
          filtered = filtered.filter(software =>
          {
            // 安全检查
            const displayName = software.displayName || ''
            const description = software.description || ''
            return displayName.toLowerCase().includes(keyword) ||
              description.toLowerCase().includes(keyword)
          })
        }
      }

      return filtered
    },

    // 已选择的软件数量
    selectedCount: (state) => state.selectedSoftware?.length || 0,

    // 是否可以生成脚本
    canGenerateScript: (state) =>
    {
      return (state.selectedSoftware?.length || 0) > 0 &&
        state.installPath &&
        state.installPath.trim().length > 0
    }
  },

  actions: {
    // 获取软件列表
    async fetchSoftwareList()
    {
      console.log('SoftwareStore: fetchSoftwareList开始')

      // 防止重复请求
      if (this.loading)
      {
        console.log('SoftwareStore: 正在加载中，跳过重复请求')
        return
      }

      this.loading = true
      console.log('SoftwareStore: 设置loading为true')

      try
      {
        console.log('SoftwareStore: 发起API请求 /software')
        const response = await api.get('/software', {
          timeout: 10000 // 10秒超时
        })

        console.log('SoftwareStore: API响应:', {
          code: response.code,
          dataLength: response.data?.length || 0,
          message: response.message
        })

        if (response.code === 200)
        {
          this.softwareList = response.data || []
          console.log('SoftwareStore: 软件列表更新成功，数量:', this.softwareList.length)
        } else
        {
          console.error('SoftwareStore: API返回错误:', response)
          throw new Error(response.message || '获取软件列表失败')
        }
      } catch (error)
      {
        console.error('SoftwareStore: 获取软件列表失败:', error)
        console.error('SoftwareStore: 错误详情:', {
          message: error.message,
          code: error.code,
          status: error.response?.status,
          statusText: error.response?.statusText,
          url: error.config?.url
        })

        // 如果是网络错误，保持现有数据
        if (error.code === 'NETWORK_ERROR' && this.softwareList.length > 0)
        {
          console.warn('SoftwareStore: 网络错误，使用缓存数据')
        } else
        {
          this.softwareList = []
        }
        throw error
      } finally
      {
        this.loading = false
        console.log('SoftwareStore: 设置loading为false')
      }
    },

    // 获取分类列表
    async fetchCategories()
    {
      try
      {
        const response = await api.get('/software/categories')
        if (response.code === 200)
        {
          this.categories = response.data
        }
      } catch (error)
      {
        console.error('获取分类列表失败:', error)
      }
    },

    // 搜索软件
    async searchSoftware(keyword)
    {
      if (!keyword || !keyword.trim())
      {
        await this.fetchSoftwareList()
        return
      }

      // 防止重复搜索
      if (this.loading)
      {
        return
      }

      this.loading = true
      try
      {
        const response = await api.get('/software/search', {
          params: { keyword: keyword.trim() },
          timeout: 8000 // 8秒超时
        })
        if (response.code === 200)
        {
          this.softwareList = response.data || []
        } else
        {
          throw new Error(response.message || '搜索失败')
        }
      } catch (error)
      {
        console.error('搜索软件失败:', error)
        // 搜索失败时不清空现有列表
        if (error.code !== 'NETWORK_ERROR')
        {
          this.softwareList = []
        }
      } finally
      {
        this.loading = false
      }
    },

    // 添加软件到选择列表
    addSoftware(software)
    {
      const exists = this.selectedSoftware.find(item => item.id === software.id)
      if (!exists)
      {
        this.selectedSoftware.push({
          id: software.id,
          name: software.name,
          displayName: software.displayName,
          version: software.latestVersion?.version || 'latest',
          category: software.category
        })
        // 持久化到本地存储
        storage.set(STORAGE_KEYS.SELECTED_SOFTWARE, this.selectedSoftware)
      }
    },

    // 从选择列表移除软件
    removeSoftware(softwareId)
    {
      const index = this.selectedSoftware.findIndex(item => item.id === softwareId)
      if (index > -1)
      {
        this.selectedSoftware.splice(index, 1)
        // 持久化到本地存储
        storage.set(STORAGE_KEYS.SELECTED_SOFTWARE, this.selectedSoftware)
      }
    },

    // 更新软件版本
    updateSoftwareVersion(softwareId, version)
    {
      const software = this.selectedSoftware.find(item => item.id === softwareId)
      if (software)
      {
        software.version = version
      }
    },

    // 清空选择列表
    clearSelectedSoftware()
    {
      this.selectedSoftware = []
      // 持久化到本地存储
      storage.set(STORAGE_KEYS.SELECTED_SOFTWARE, this.selectedSoftware)
    },

    // 生成脚本
    async generateScript()
    {
      if (!this.canGenerateScript)
      {
        throw new Error('请选择软件并设置安装路径')
      }

      this.loading = true
      try
      {
        // 开源版本跳过脚本生成API调用
        const isOpenSourceVersion = true // 开源版本标识
        if (isOpenSourceVersion)
        {
          console.log('📊 开源版本跳过脚本生成API调用')
          // 返回模拟的脚本内容
          const mockScript = `# DevEnv OpenSource 版本
# 开源版本暂不支持自动脚本生成功能
# 以下是您选择的软件列表：

${this.selectedSoftware.map(software =>
            `# - ${software.displayName} (${software.name}) v${software.version}`
          ).join('\n')}

# 请手动安装上述软件
echo "DevEnv OpenSource - 软件安装脚本"
echo "开源版本暂不支持自动脚本生成，请手动安装所选软件"
`
          this.generatedScript = mockScript
          return mockScript
        }

        const request = {
          os: this.selectedOs,
          softwareList: this.selectedSoftware,
          installPath: this.installPath,
          options: this.scriptOptions
        }

        const response = await api.post('/script/generate', request)
        if (response.code === 200)
        {
          this.generatedScript = response.data
          return response.data
        } else
        {
          throw new Error(response.message)
        }
      } catch (error)
      {
        console.error('生成脚本失败:', error)
        throw error
      } finally
      {
        this.loading = false
      }
    },

    // 设置搜索关键词
    setSearchKeyword(keyword)
    {
      this.searchKeyword = keyword
      storage.set(STORAGE_KEYS.SEARCH_KEYWORD, keyword)
    },

    // 设置选择的分类
    setSelectedCategory(category)
    {
      this.selectedCategory = category
      storage.set(STORAGE_KEYS.SELECTED_CATEGORY, category)
    },

    // 设置选择的操作系统
    setSelectedOs(os)
    {
      this.selectedOs = os
      storage.set(STORAGE_KEYS.SELECTED_OS, os)

      // 根据操作系统设置默认安装路径
      let defaultPath
      switch (os)
      {
        case 'windows':
          defaultPath = 'C:\\DevEnv'
          break
        case 'linux':
          defaultPath = '/opt/devenv'
          break
        case 'macos':
          defaultPath = '/Applications/DevEnv'
          break
        default:
          defaultPath = 'C:\\DevEnv'
      }
      this.installPath = defaultPath
      storage.set(STORAGE_KEYS.INSTALL_PATH, defaultPath)
    },

    // 设置安装路径
    setInstallPath(path)
    {
      this.installPath = path
      storage.set(STORAGE_KEYS.INSTALL_PATH, path)
    },

    // 更新脚本选项
    updateScriptOptions(options)
    {
      this.scriptOptions = { ...this.scriptOptions, ...options }
    },

    // 更新脚本配置
    updateScriptConfig(config)
    {
      this.scriptConfig = { ...this.scriptConfig, ...config }

      // 持久化到本地存储
      storage.set(STORAGE_KEYS.SCRIPT_CONFIG, this.scriptConfig)

      // 同步到旧的字段以保持兼容性
      if (config.os)
      {
        this.selectedOs = config.os
        storage.set(STORAGE_KEYS.SELECTED_OS, config.os)
      }
      if (config.installPath)
      {
        this.installPath = config.installPath
        storage.set(STORAGE_KEYS.INSTALL_PATH, config.installPath)
      }
      if (config.enableResume !== undefined ||
        config.enableVerification !== undefined ||
        config.enableAutoPath !== undefined ||
        config.mirrorRegion !== undefined)
      {
        this.scriptOptions = {
          enableResume: config.enableResume ?? this.scriptOptions.enableResume,
          enableVerification: config.enableVerification ?? this.scriptOptions.enableVerification,
          enableAutoPath: config.enableAutoPath ?? this.scriptOptions.enableAutoPath,
          mirrorRegion: config.mirrorRegion ?? this.scriptOptions.mirrorRegion
        }
      }
    },

    // 获取脚本配置
    getScriptConfig()
    {
      // 确保状态同步
      const config = {
        ...this.scriptConfig,
        os: this.selectedOs || this.scriptConfig.os,
        installPath: this.installPath || this.scriptConfig.installPath
      }

      // 同步回scriptConfig以保持一致性
      this.scriptConfig = { ...config }

      return config
    }
  }
})
